package cn.com.cnxfs.relaxchat;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity{
    EditText username,password,password2,newNickname;
    private Runnable _login; //登录线程，注册后可以直接调用这个线程马上登录

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        final SharedPreferences preferences = getSharedPreferences("db_login",MODE_PRIVATE);
        String id = preferences.getString("id","");
        //String username = preferences.getString("username","");
        //String nickname = preferences.getString("nickname","");
        String loginServer_addr = preferences.getString("loginServer_addr", "");
        String mqttServer_addr = preferences.getString("mqttServer_addr", "");
        assert id != null;
        if(!id.equals("")){//检测是否已经登录
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish(); //关掉登录页面
        }
        // 保存服务器地址
        assert loginServer_addr != null;
        if(loginServer_addr.equals(""))
            preferences.edit().putString("loginServer_addr", Api.url[0]).apply();
        else
            Api.url[0] = loginServer_addr;
        assert mqttServer_addr != null;
        if(mqttServer_addr.equals(""))
            preferences.edit().putString("mqttServer_addr", Api.mqttServer[0]).apply();
        else
            Api.mqttServer[0] = mqttServer_addr;

        final TextView newPassword = findViewById(R.id.label_password2);
        final TextView new_nickname = findViewById(R.id.label_new_nickname);
        Button button_login = findViewById(R.id.button_login);
        Button button_register = findViewById(R.id.button_register);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        password2 = findViewById(R.id.password2);
        newNickname = findViewById(R.id.newnickname);

        newPassword.setVisibility(View.INVISIBLE); //设置确认密码不可见，注册的时候才能看见
        new_nickname.setVisibility(View.INVISIBLE);
        password2.setVisibility(View.INVISIBLE);
        newNickname.setVisibility(View.INVISIBLE);
        button_login.setOnClickListener(new View.OnClickListener() { //登录按钮按下动作
            @Override
            public void onClick(View v) {
                new Thread(_login).start();
            }
        });

        button_register.setOnClickListener(new View.OnClickListener() { //注册按钮按下动作
            @Override
            public void onClick(View v) {
                newPassword.setVisibility(View.VISIBLE); //设置确认密码可见
                new_nickname.setVisibility(View.VISIBLE);
                password2.setVisibility(View.VISIBLE);
                newNickname.setVisibility(View.VISIBLE);
                final String newpass = password2.getText().toString();
                final String usrname = username.getText().toString();
                final String nikname = newNickname.getText().toString();
                if(usrname.equals(""))
                    Toast.makeText(LoginActivity.this,"请输入用户名！",Toast.LENGTH_SHORT).show();
                else if(newpass.equals(""))
                    Toast.makeText(LoginActivity.this,"请输入确认密码！",Toast.LENGTH_SHORT).show();
                else if(nikname.equals(""))
                    Toast.makeText(LoginActivity.this,"请输入新昵称！",Toast.LENGTH_SHORT).show();
                else if(newpass.equals(password.getText().toString())){ //确认密码与新密码一致
                    new Thread(new Runnable() { //新线程发送网络请求
                        @Override
                        public void run() {
                            try{  //先检测用户名是否存在
                                FormBody.Builder params = new FormBody.Builder();
                                params.add("username",usrname); //添加url参数
                                OkHttpClient client = new OkHttpClient();
                                Request request = new Request.Builder()
                                        .url(Api.url[0]+"/login/search").post(params.build())
                                        .build();
                                Response response = client.newCall(request).execute(); //执行发送指令
                                String responseData = response.body().string();
                                if(responseData.equals("")){  //用户名可以用
                                    String passwd = MD5Utils.encode(newpass); //MD5加密
                                    try{
                                        String json = "{\"username\": \""+usrname+"\", \"password\": \""+passwd+"\", \"nickname\": \""+nikname+"\"}";
                                        request = new Request.Builder()
                                                .url(Api.url[0]+"/login/add")
                                                .post(RequestBody.create(MediaType.parse("application/json"),json))
                                                .build();
                                        response = client.newCall(request).execute(); //执行发送指令
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(LoginActivity.this,"注册成功！",Toast.LENGTH_SHORT).show();
                                                new Thread(_login).start(); //自动登录
                                                newPassword.setVisibility(View.INVISIBLE); //设置确认密码不可见，注册的时候才能看见
                                                new_nickname.setVisibility(View.INVISIBLE);
                                                password2.setVisibility(View.INVISIBLE);
                                                newNickname.setVisibility(View.INVISIBLE);
                                            }
                                        });
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }else{
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this,"该用户名已存在！",Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }else
                    Toast.makeText(LoginActivity.this,"新密码与确认密码不一致！请检查！",Toast.LENGTH_SHORT).show();
            }
        });

        _login = new Runnable() { //登录线程
            @Override
            public void run() {
                String usrname = username.getText().toString();
                String passwd = password.getText().toString();
                passwd = MD5Utils.encode(passwd); //MD5加密
                try{
                    String json = "{\"username\": \""+usrname+"\", \"password\": \""+passwd+"\"}";
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            //不能用127.0.0.1，因为此时的本地是电脑，不是模拟器
                            .url(Api.url[0]+"/login/login")
                            .post(RequestBody.create(MediaType.parse("application/json"),json))
                            .build();
                    Response response = client.newCall(request).execute(); //执行发送指令
                    String responseData = response.body().string();
                    Log.d("登录请求回复",responseData);
                    if(responseData.equals("")){  //登录失败，后端返回空串
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this,"用户名或密码错误！",Toast.LENGTH_SHORT).show();
                                username.setText("");
                                password.setText("");
                            }
                        });
                    }else {
                        try{ //解析JSON
                            JSONObject jsonObject = new JSONObject(responseData);
                            String id = jsonObject.getString("id");
                            String nickname = jsonObject.getString("nickname");
                            //写入用户信息到永久储存
                            SharedPreferences.Editor editor = getSharedPreferences("db_login",MODE_PRIVATE).edit();
                            editor.putString("id",id);
                            editor.putString("username",usrname);
                            editor.putString("nickname",nickname);
                            editor.apply();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this,"登录成功！",Toast.LENGTH_SHORT).show();
                                    password.setText("");
                                }
                            });
                            //跳转到登录后的页面
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish(); //关掉登录页面
                        }catch (Exception e){
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),"登录失败！",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"登录超时！请检查网络连接！",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };

        TextView setServer = findViewById(R.id.set_server);
        setServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                builder.setTitle("设置服务器");
                final View view2 = getLayoutInflater().inflate(R.layout.layout_change_server, null);
                final TextView loginServerAddr = view2.findViewById(R.id.pass1);
                final TextView mqttServerAddr = view2.findViewById(R.id.pass2);
                loginServerAddr.setText(Api.url[0]);
                mqttServerAddr.setText(Api.mqttServer[0]);
                builder.setView(view2);
                builder.setCancelable(false);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String server1 = loginServerAddr.getText().toString();
                        String server2 = mqttServerAddr.getText().toString();
                        // 编译正则表达式
                        Pattern pattern1 = Pattern.compile("http://[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{1,}");
                        Matcher matcher1 = pattern1.matcher(server1);
                        Pattern pattern2 = Pattern.compile("tcp://[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{1,}");
                        Matcher matcher2 = pattern2.matcher(server2);
                        // 字符串是否与正则表达式相匹配
                        if(matcher1.matches() &&matcher2.matches()){
                            Api.url[0] = server1;
                            Api.mqttServer[0] = server2;
                            preferences.edit().putString("loginServer_addr", server1).apply();
                            preferences.edit().putString("mqttServer_addr", server2).apply();
                            Toast.makeText(LoginActivity.this,"设置成功！",Toast.LENGTH_SHORT).show();
                        }
                        else
                            Toast.makeText(LoginActivity.this, "IP地址输入格式有误！", Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
            }
        });
    }
}

class MD5Utils {
    public static String encode(String str) {
        StringBuffer buffer = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes());
            for (byte b : digest) {
                int x = b & 0xff;  // 将byte转换2位的16进制int类型数
                String s = Integer.toHexString(x); // 将一个int类型的数转为2位的十六进制数
                if (s.length() == 1) {
                    s = "0" + s;
                }
                buffer.append(s);
                //Log.d("vivi", "encode: " + s);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}
